package com.steam.splace;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


import bo.DirectionsJSONParser;
import bo.UserFunctions;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.internal.al;
import com.google.android.gms.internal.p;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import dao.DataAccess;
import dao.MySQLiteHelper;
import entity.Category;
import entity.Comment;
import entity.Message;
import entity.Place;
import entity.Region;

import thread.DoThread;
import thread.DoThreadGet;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.TextureView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ViewPlaceActivity extends FragmentActivity implements LocationListener{
	private final int place_tag =10;
	GoogleMap googleMap;
	ListView listComment;
    private final int getfavorite_tag =9;
    private final int addfavorite_tag =17;
    private final int addVote_tag =18;
    private final int getComment_tag =11;
    private final int addComment_tag =12;
    private final int deleteComment_tag =13;
    private final int report_tag =16;
	float zoomlevel=12;float distance=0;
	Location location ;
	Activity currentActivity;
	Menu menu;Handler handler;MenuItem menux;
	int uid=-2;
	String provider;
	int votePoint=1;
	LocationManager locationmanager;
	Spinner spVote;
	int positionOnListView=-1;
	PolylineOptions rectLine;
	int pid;
	ContextMenu contextMenu;
	Button bt;
	ArrayList<LatLng> markerPoints;

	 double lat=0;double lng=0;
	Button btAddFavorite;
	ArrayAdapter<Comment>arrayAdapter;
	ArrayList<Message> arr;
	Place currentPlace;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);
		setContentView(R.layout.viewplace_activity);
		Intent intent=getIntent();
		pid=intent.getIntExtra("pid", 0);
		//disable bt comment
				setBtcomment();
				
				System.out.println("uid"+uid);
				currentActivity=this;
				if(uid>-1){
				spVote=(Spinner)this.findViewById(R.id.spVote);
				ArrayList<String> list=new ArrayList<String>();
				list.add("Rất tệ");
				list.add("Tệ");
				list.add("Tạm được");
				list.add("Ngon");
				list.add("Rất ngon");
				ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
						android.R.layout.simple_spinner_item, list);
					dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					spVote.setAdapter(dataAdapter);
					spVote.setOnItemSelectedListener(new MyEvent());}
				SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
				// Getting GoogleMap object from the fragment
				googleMap = fm.getMap();
				googleMap.setMyLocationEnabled(true);
				googleMap.animateCamera(CameraUpdateFactory.zoomTo(zoomlevel));
				
				
				locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
		        Criteria cr = new Criteria();
		         provider = locationmanager.getBestProvider(cr, false);

					//locationmanager.requestLocationUpdates(provider, 1000, 0, this);
		        location = locationmanager.getLastKnownLocation(provider);

		        if (location != null) {
		        	lat=location.getLatitude();
			        lng=location.getLongitude();
		        }
		btAddFavorite=(Button)findViewById(R.id.btaddFavorite);
		handler=new Handler(){
			 @Override
			 public void handleMessage(Message msg){ 
				 if(msg.what==5){
					 if(lat!=0&&lng!=0&&currentPlace!=null){
				       LatLng point=new LatLng(lat,lng);
				      LatLng des=new LatLng(currentPlace.getLatitude(),currentPlace.getLongitude());
				      markerPoints=new ArrayList<LatLng>();
						 markerPoints.add(point);
						 markerPoints.add(des);
						 if(markerPoints.size() >= 2){
			                LatLng origin = markerPoints.get(0);
			                LatLng dest = markerPoints.get(1);
			                
			                googleMap.addPolyline(rectLine);
			                //TextView desPlace=(TextView)currentActivity.findViewById(R.id.lbplaceDistance);
			                //desPlace.setText("Khoảng cách"+distance);
	/*		                // Getting URL to the Google Directions API
			                String url = getDirectionsUrl(origin, dest);
			                DownloadTask downloadTask = new DownloadTask();

			                // Start downloading json data from Google Directions API
			                try{
			                downloadTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, url);}
			                catch(NullPointerException ex){
			                	Toast toast=Toast.makeText(currentActivity, "Lỗi chỉ đường!!",
			    						1000);
			    				toast.setGravity(Gravity.CENTER, 0, 0);
			    				toast.show();
			                	
			                }*/
			            }
						 }
				 }
		 if(msg.what==3){
					 
					 TextView votepoint=(TextView)findViewById(R.id.tvVotePoint);
					 double[] voteReturn=(double[]) msg.obj;
					 votepoint.setText(voteReturn[1]+"");
					 double votePoint=Double.parseDouble(voteReturn[1]+"");
					 Button btVote1=(Button)findViewById(R.id.btVote1);
					 ImageView iv=(ImageView)currentActivity.findViewById(R.id.ivVotePoitn);
					 if(votePoint==0){
						 iv.setImageResource(R.drawable.s0); 
					 }
					 if(votePoint<=1.5&&votePoint>0){
						 iv.setImageResource(R.drawable.s11); 
					 }
					 if(votePoint<2.5&&votePoint>1.5){
						 iv.setImageResource(R.drawable.s2); 
					 }
					 if(votePoint<3.5&&votePoint>2.5){
						 iv.setImageResource(R.drawable.s3); 
					 }
					 if(votePoint<4.5&&votePoint>3.5){
						 iv.setImageResource(R.drawable.s4); 
					 }
					 if(votePoint==5){
						 iv.setImageResource(R.drawable.s5); 
					 }
					 
					 if(uid==-1||voteReturn[0]==1){
						 Spinner sp=(Spinner)currentActivity.findViewById(R.id.spVote);
						 System.out.println("voteeeee:"+voteReturn[0]+"/"+uid);
						 sp.setVisibility(View.GONE);
						 btVote1.setVisibility(View.GONE);
					 }
				 }
				 
				 
				 if(msg.what==2){
					 	arr=(ArrayList<Message> )msg.obj;
						
						if(uid!=-1){
						boolean isExistFavorite=false;
						for (Message fav : arr) {
							if(fav.getPlaceid()==pid){
								isExistFavorite=true;
							break;	
							}
						}
						if(isExistFavorite==true||uid==-1)
							btAddFavorite.setVisibility(View.GONE);}
						else btAddFavorite.setVisibility(View.GONE);
				 }
		}
		};
		loadVoteAndFav();
		listComment=(ListView)findViewById(R.id.listComment);
		registerForContextMenu(listComment);
		
		DoThreadGet thread=new DoThreadGet(ViewPlaceActivity.this);
		ArrayList params=new ArrayList();
		params.add(place_tag);
		params.add(pid);
		params.add(googleMap);
		params.add(arrayAdapter);
		//LatLng point=new LatLng(lat,lng);
		//params.add(point);
		thread.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, params);
      
		Thread t=new Thread(new Runnable() {
			@Override
			public void run() {
				
				UserFunctions user=new UserFunctions();
				user.setActivity(currentActivity);
				currentPlace= user.getPlace(pid);
				
				GMapV2Direction md = new GMapV2Direction();

                Document doc = md.getDocument(new LatLng(lat,lng), new LatLng(currentPlace.getLatitude(), currentPlace.getLongitude()), GMapV2Direction.MODE_DRIVING);
                ArrayList<LatLng> directionPoint = md.getDirection(doc);
                 rectLine = new PolylineOptions().width(3).color(Color.RED);
                for(int i = 0 ; i < directionPoint.size() ; i++) {          
                rectLine.add(directionPoint.get(i));
                }
                //distance=md.getDistanceValue(doc);
                
				Message msg=handler.obtainMessage(5, 1);
				handler.sendMessage(msg);
				}
			
		});
		t.start();
		}
	private class MyEvent implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			votePoint = arg2+1;
			Log.v("position",arg2+"");
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}
	
	}
	private void loadVoteAndFav(){
		Thread t2=new Thread(new Runnable() {
			@Override
			public void run() {
				UserFunctions user=new UserFunctions();
				user.setActivity(currentActivity);
				double[] arr=user.getVote(pid);
				Message msg=handler.obtainMessage(3, arr);
				handler.sendMessage(msg);

				
			}
		});
		t2.start();
		if(uid!=-1){
Thread t=new Thread(new Runnable() {
			@Override
			public void run() {
				if(uid!=-1){
				UserFunctions user=new UserFunctions();
				user.setActivity(currentActivity);
				ArrayList<Message> arr=user.getFavorite();
				Message msg=handler.obtainMessage(2, arr);
				handler.sendMessage(msg);
				}
				
			}
		});
		t.start();}else btAddFavorite.setVisibility(View.GONE);
	}
	private String getDirectionsUrl(LatLng origin,LatLng dest){
   	 
        // Origin of route
        String str_origin = "origin="+origin.latitude+","+origin.longitude;
 
        // Destination of route
        String str_dest = "destination="+dest.latitude+","+dest.longitude;
 
        // Sensor enabled
        String sensor = "sensor=false";
 
        // Building the parameters to the web service
        String parameters = str_origin+"&"+str_dest+"&"+sensor;
 
        // Output format
        String output = "json";
 
        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
 
        return url;
    }
	  @Override
	  protected void onResume() {
	    super.onResume();
	    locationmanager.requestLocationUpdates(provider, 400, 1, this);
	  }
	  @Override
	  protected void onPause() {
	    super.onPause();
	    locationmanager.removeUpdates(this);
	  }
	private void setBtcomment() {
		DataAccess da=new DataAccess(this);
		 bt=	(Button) this.findViewById(R.id.btAddComment);
		if(uid==-1){
			Button btaddF=(Button)findViewById(R.id.btaddFavorite);
			Button btVot1=(Button)findViewById(R.id.btVote1);
			Button btReport=(Button)findViewById(R.id.btReport);
			EditText txtComment=(EditText)findViewById(R.id.txtCommentContent);
			txtComment.setVisibility(View.GONE);
			btVot1.setVisibility(View.GONE);
			Spinner sp=(Spinner)this.findViewById(R.id.spVote);
			sp.setVisibility(View.GONE);
			btReport.setVisibility(View.GONE);
			bt.setVisibility(View.GONE);
		}
		else bt.setVisibility(View.VISIBLE);
	}
	
	private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);
 
            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();
 
            // Connecting to url
            urlConnection.connect();
 
            // Reading data from url
            iStream = urlConnection.getInputStream();
 
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
 
            StringBuffer sb = new StringBuffer();
 
            String line = "";
            while( ( line = br.readLine()) != null){
                sb.append(line);
            }
 
            data = sb.toString();
            br.close();
            System.out.println("Data"+sb.toString());
        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }
    
    private class DownloadTask extends AsyncTask<String, Void, String>{
    	 
        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {
 
            // For storing data from web service
            String data = "";
 
            try{
                // Fetching the data from web service
                data = downloadUrl(url[0]);
                
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }
 
        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
 
            ParserTask parserTask = new ParserTask();
            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
        }
    }
    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
    	 
        // Parsing the data in non-ui thread
        protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
 
            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;
 
            try{
                jObject = new JSONObject(jsonData[0]);
                
                DirectionsJSONParser parser = new DirectionsJSONParser();
 
                // Starts parsing data
                routes = parser.parse(jObject);
            }catch(Exception e){
                e.printStackTrace();
            }
            return routes;
        }
        protected void onPostExecute(List<List<HashMap<String, String>>> result) {
            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();
 
            // Traversing through all the routes
            for(int i=0;i<result.size();i++){
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();
 
                // Fetching i-th route
                List<HashMap<String, String>> path = result.get(i);
 
                // Fetching all the points in i-th route
                for(int j=0;j<path.size();j++){
                    HashMap<String,String> point = path.get(j);
 
                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);
 
                    points.add(position);
                }
 
                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points);
                lineOptions.width(8);
                lineOptions.color(Color.RED);
                
            }
 
            // Drawing polyline in the Google Map for the i-th route
            try{
            googleMap.addPolyline(lineOptions);}
            catch(Exception ex){Toast toast=Toast.makeText(currentActivity, "Thôi dừng lại đi. Nơi đó có cá mập :v!!",
					1000);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();}
        }
    }
    
    
	public void loadComment(){
		DoThreadGet getComments=new DoThreadGet(ViewPlaceActivity.this);
		ArrayList paramsComment=new ArrayList();
		paramsComment.add(getComment_tag);
		paramsComment.add(pid);
		paramsComment.add(arrayAdapter);
		getComments.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, paramsComment);
	}
	public void onClick(View view) {

		int id = view.getId();
		if (id == R.id.btReport) {
			AlertDialog.Builder alert = new AlertDialog.Builder(ViewPlaceActivity.this);
			alert.setTitle("Báo cáo sai phạm");
			alert.setMessage("Nội dung");
			// Set an EditText view to get user input 
			 final EditText input = new EditText(this);
			//final SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
			 alert.setView(input);
			alert.setPositiveButton("Gửi", new DialogInterface.OnClickListener() {
			 public void onClick(DialogInterface dialog, int whichButton) {
			   String value = input.getText().toString();
				 List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("itemid", pid+""));
					params.add(new BasicNameValuePair("itemtype", 1+""));
						params.add(new BasicNameValuePair("description", value));
					System.out.println(value);
					ArrayList l=new ArrayList();
					l.add(report_tag);
					l.add(params);
					DoThread sendReport=new DoThread(currentActivity);
					sendReport.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, l);
					
			   }
			 });
			alert.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
			   public void onClick(DialogInterface dialog, int whichButton) {
			     // Canceled.
				   dialog.cancel();
			   }
			 }).create().show();
		} else if (id == R.id.btaddFavorite) {
			DoThread addFavorite=new DoThread(ViewPlaceActivity.this);
			ArrayList paramsFavorite=new ArrayList();
			List<NameValuePair> paramsFav = new ArrayList<NameValuePair>();
			paramsFav.add(new BasicNameValuePair("placeid", pid+""));
			paramsFavorite.add(addfavorite_tag);
			paramsFavorite.add(paramsFav);
			addFavorite.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, paramsFavorite);
		} else if (id == R.id.btVote1) {
			DoThread addVote=new DoThread(ViewPlaceActivity.this);
			ArrayList votes=new ArrayList();
			List<NameValuePair> paramsVote = new ArrayList<NameValuePair>();
			paramsVote.add(new BasicNameValuePair("placeid", pid+""));
			paramsVote.add(new BasicNameValuePair("point", votePoint+""));
			votes.add(addVote_tag);
			votes.add(paramsVote);
			addVote.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, votes);
		} else if (id == R.id.btAddComment) {
			EditText commentContent=(EditText)this.findViewById(R.id.txtCommentContent);
			if(uid!=-1){
				
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("userid", uid+""));
				try {
					params.add(new BasicNameValuePair("content", commentContent.getText().toString()));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				params.add(new BasicNameValuePair("placeid", pid+""));
				
				ArrayList l=new ArrayList();
				l.add(addComment_tag);
				l.add(params);
				l.add(arrayAdapter);
			DoThread thread=new DoThread(ViewPlaceActivity.this);
			thread.execute(l);
			}
		}
		}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);

		//uid=getUID();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);
		if(uid!=-1){
			
			getMenuInflater().inflate(R.menu.main, menu);
		}
		else getMenuInflater().inflate(R.menu.menunologin, menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		if (item.getItemId() == R.id.menuSearch) {
			if (!this.getClass().getSimpleName().equals("SearchActivity")) {

				Intent searchIntent = new Intent(this, SearchActivity.class);
				startActivity(searchIntent);
			}
		} else if (item.getItemId() == R.id.menuProfile) {
			if (!this.getClass().getSimpleName().equals("ProfileActivity")) {
				Intent profileIntent = new Intent(this, ProfileActivity.class);
				startActivity(profileIntent);
			}
		}
		else if(item.getItemId() == R.id.SignOut){
			DataAccess da=new DataAccess(this);
			try {
				da.open();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			da.signOut();
			da.close();
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
			Editor prefsEditor = prefs.edit(); 
			prefsEditor.putInt("uid", -1);
			prefsEditor.putString("token", "");
				prefsEditor.commit();
			this.finish();
			Intent loginIntent = new Intent(this, MainActivity.class);
			startActivity(loginIntent);
		}
		else if(item.getItemId() == R.id.menuSignUp){
			if (!this.getClass().getSimpleName().equals("SignUpActivity")) {

				Intent signUpActivity = new Intent(this, SignUpActivity.class);
				startActivity(signUpActivity);
			}
		}
		else if(item.getItemId() == R.id.menuForgot){
			if (!this.getClass().getSimpleName().equals("ForgotPasswordActivity")) {
				Intent forgotPasswordActivity = new Intent(this, ForgotPasswordActivity.class);
				startActivity(forgotPasswordActivity);
			}
		}
		else if(item.getItemId() == R.id.menuAddPlace){
			if (!this.getClass().getSimpleName().equals("AddPlaceActivity")) {
				Intent addPlaceActivity = new Intent(this, AddPlaceActivity.class);
				startActivity(addPlaceActivity);
			}
		}
		else if(item.getItemId() == R.id.menuSignIn){
			if (!this.getClass().getSimpleName().equals("MainActivity")) {
				Intent mainActivity = new Intent(this, MainActivity.class);
				startActivity(mainActivity);
			}
		}
		else if(item.getItemId() == R.id.menuSearchArea){
			if (!this.getClass().getSimpleName().equals("SearchByAreaActivity")) {
				Intent mainActivity = new Intent(this, SearchByAreaActivity.class);
				startActivity(mainActivity);
			}
		}else if(item.getItemId() == R.id.menuFavorite){
			if (!this.getClass().getSimpleName().equals("FavoriteActivity")) {

				Intent favoriteActivity = new Intent(this, FavoriteActivity.class);
				startActivity(favoriteActivity);
			}
		}
		/*else if (item.getItemId() != R.id.menuSearchArea
				&&item.getItemId() != R.id.menuSearch
				&& item.getItemId() != R.id.menuProfile
						&& item.getItemId() != R.id.SignOut
								&& item.getItemId() != R.id.menuSignUp
										&& item.getItemId() != R.id.menuForgot
												&& item.getItemId() != R.id.menuAddPlace
														&& item.getItemId() != R.id.menuSignIn
													&& item.getItemId() != 10) {
			Intent placeIntent = new Intent(this, ViewPlaceActivity.class);
			placeIntent.putExtra("pid", item.getItemId());
			startActivity(placeIntent);
		}*/
		return true;
	}
	@Override
	public void onLocationChanged(Location arg0) {
		// Getting latitude of the current location
				location.setLatitude(arg0.getLatitude());
				location.setLongitude(arg0.getLongitude());
				// Getting longitude of the current location
				// Creating a LatLng object for the current location
		
	}
	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}
	@Override
	 public void onCreateContextMenu(ContextMenu menu, View v,
	 ContextMenuInfo menuInfo) {
	 // TODO Auto-generated method stub
	 super.onCreateContextMenu(menu, v, menuInfo);
	 getMenuInflater()
	 .inflate(R.menu.contextmenu, menu);
	 contextMenu=menu;
	 }
	 @Override
	 public boolean onContextItemSelected(MenuItem item) {
	 int itemId = item.getItemId();
	if (itemId == R.id.menuReport) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Báo cáo sai phạm");
		alert.setMessage("Nội dung");
		// Set an EditText view to get user input 
		 final EditText input = new EditText(this);
		alert.setView(input);
		menux=item;
		alert.setPositiveButton("Gửi", new DialogInterface.OnClickListener() {
		 public void onClick(DialogInterface dialog, int whichButton) {
		   String value = input.getText().toString();
		   AdapterContextMenuInfo menuInfo =(AdapterContextMenuInfo)menux.getMenuInfo();
			 Comment comment = (Comment) listComment.getAdapter().getItem(menuInfo.position);
			 List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("itemid", comment.getId()+""));
				params.add(new BasicNameValuePair("itemtype", 2+""));
				params.add(new BasicNameValuePair("description", value));
				ArrayList l=new ArrayList();
				l.add(report_tag);
				l.add(params);
				DoThread sendReport=new DoThread(currentActivity);
				sendReport.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, l);
				
		   }
		 });
		alert.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
		   public void onClick(DialogInterface dialog, int whichButton) {
		     // Canceled.
		   }
		 });
		alert.show();
	}
	 return super.onContextItemSelected(item);
	 }
	 
	 
	 public class GMapV2Direction {
		    public final static String MODE_DRIVING = "driving";
		    public final static String MODE_WALKING = "walking";

		    public GMapV2Direction() { }

		    public Document getDocument(LatLng start, LatLng end, String mode) {
		        String url = "http://maps.googleapis.com/maps/api/directions/xml?" 
		                + "origin=" + start.latitude + "," + start.longitude  
		                + "&destination=" + end.latitude + "," + end.longitude 
		                + "&sensor=false&units=metric&mode="+mode;

		        try {
		            HttpClient httpClient = new DefaultHttpClient();
		            HttpContext localContext = new BasicHttpContext();
		            HttpPost httpPost = new HttpPost(url);
		            HttpResponse response = httpClient.execute(httpPost, localContext);
		           /* StringBuffer sb=new StringBuffer();
		            BufferedReader rd = new BufferedReader(new InputStreamReader(
							response.getEntity().getContent()));
					String line = "";
					while ((line = rd.readLine()) != null) {
						sb.append(line);
					}
					System.out.println();*/
		            InputStream in = response.getEntity().getContent();
		            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		            Document doc = builder.parse(in);
		            System.out.println(doc.toString());
		            return doc;
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        return null;
		    }

		    public String getDurationText (Document doc) {
		        NodeList nl1 = doc.getElementsByTagName("duration");
		        Node node1 = nl1.item(0);
		        NodeList nl2 = node1.getChildNodes();
		        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
		        Log.i("DurationText", node2.getTextContent());
		        return node2.getTextContent();
		    }

		    public int getDurationValue (Document doc) {
		        NodeList nl1 = doc.getElementsByTagName("duration");
		        Node node1 = nl1.item(0);
		        NodeList nl2 = node1.getChildNodes();
		        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
		        Log.i("DurationValue", node2.getTextContent());
		        return Integer.parseInt(node2.getTextContent());
		    }

		    public String getDistanceText (Document doc) {
		    	String value="";
		    	NodeList nl1 = doc.getElementsByTagName("distance");
		        for (int i = 0; i < nl1.getLength(); i++) {
		        Node node1 = nl1.item(i);
		        NodeList nl2 = node1.getChildNodes();
		        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
		        value+=node2.getTextContent();
		        }
		        return value;
		    }

		    public float getDistanceValue (Document doc) {
		    	float dis=0;
		        NodeList nl1 = doc.getElementsByTagName("distance");
		        for (int i = 0; i < nl1.getLength(); i++) {
		        Node node1 = nl1.item(i);
		        NodeList nl2 = node1.getChildNodes();
		        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
		        if(node2.getTextContent().contains("km"))
		        dis+=Float.parseFloat(node2.getTextContent().substring(0,node2.getTextContent().length()-2).trim());
		        else dis+=Float.parseFloat(node2.getTextContent().substring(0,node2.getTextContent().length()-2).trim())/1000;
		        Log.i("DistanceValue", node2.getTextContent());
		        }
		        
		        return dis;
		    }

		    public String getStartAddress (Document doc) {
		        NodeList nl1 = doc.getElementsByTagName("start_address");
		        Node node1 = nl1.item(0);
		        Log.i("StartAddress", node1.getTextContent());
		        return node1.getTextContent();
		    }

		    public String getEndAddress (Document doc) {
		        NodeList nl1 = doc.getElementsByTagName("end_address");
		        Node node1 = nl1.item(0);
		        Log.i("StartAddress", node1.getTextContent());
		        return node1.getTextContent();
		    }

		    public String getCopyRights (Document doc) {
		        NodeList nl1 = doc.getElementsByTagName("copyrights");
		        Node node1 = nl1.item(0);
		        Log.i("CopyRights", node1.getTextContent());
		        return node1.getTextContent();
		    }

		    public ArrayList<LatLng> getDirection (Document doc) {
		        NodeList nl1, nl2, nl3;
		        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
		        nl1 = doc.getElementsByTagName("step");
		        if (nl1.getLength() > 0) {
		            for (int i = 0; i < nl1.getLength(); i++) {
		                Node node1 = nl1.item(i);
		                nl2 = node1.getChildNodes();

		                Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
		                nl3 = locationNode.getChildNodes();
		                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
		                double lat = Double.parseDouble(latNode.getTextContent());
		                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
		                double lng = Double.parseDouble(lngNode.getTextContent());
		                listGeopoints.add(new LatLng(lat, lng));

		                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
		                nl3 = locationNode.getChildNodes();
		                latNode = nl3.item(getNodeIndex(nl3, "points"));
		                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
		                for(int j = 0 ; j < arr.size() ; j++) {
		                    listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
		                }

		                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
		                nl3 = locationNode.getChildNodes();
		                latNode = nl3.item(getNodeIndex(nl3, "lat"));
		                lat = Double.parseDouble(latNode.getTextContent());
		                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
		                lng = Double.parseDouble(lngNode.getTextContent());
		                listGeopoints.add(new LatLng(lat, lng));
		            }
		        }

		        return listGeopoints;
		    }

		    private int getNodeIndex(NodeList nl, String nodename) {
		        for(int i = 0 ; i < nl.getLength() ; i++) {
		            if(nl.item(i).getNodeName().equals(nodename))
		                return i;
		        }
		        return -1;
		    }

		    private ArrayList<LatLng> decodePoly(String encoded) {
		        ArrayList<LatLng> poly = new ArrayList<LatLng>();
		        int index = 0, len = encoded.length();
		        int lat = 0, lng = 0;
		        while (index < len) {
		            int b, shift = 0, result = 0;
		            do {
		                b = encoded.charAt(index++) - 63;
		                result |= (b & 0x1f) << shift;
		                shift += 5;
		            } while (b >= 0x20);
		            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
		            lat += dlat;
		            shift = 0;
		            result = 0;
		            do {
		                b = encoded.charAt(index++) - 63;
		                result |= (b & 0x1f) << shift;
		                shift += 5;
		            } while (b >= 0x20);
		            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
		            lng += dlng;

		            LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
		            poly.add(position);
		        }
		        return poly;
		    }
		}
}
